package pl.freetimetool.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import pl.freetimetool.domain.Project;

public class ProjectDaoImpl implements ProjectDao {

	@PersistenceContext
	EntityManager entityManager;

	public Project findProject(final String projectName) {
		final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
		final CriteriaQuery<Project> c = cb.createQuery(Project.class);
		final Root<Project> r = c.from(Project.class);
		try {
			c.select(r).where(cb.equal(r.get("projectName"), projectName));
			return this.entityManager.createQuery(c).getSingleResult();
		} catch (final NoResultException nre) {
			return null;
		}
	}

	public void saveProject(final Project project) {
		this.entityManager.persist(project);
	}

	public void deleteProjectFromDatabase(final Project project) {
		this.entityManager.remove(project);
	}

	public List<Project> findAllProjects() {
		return this.entityManager.createQuery("SELECT a FROM Project a", Project.class).getResultList();
	}
}
